1759F - All Possible Digits - CodeForces Solution


binary search data structures greedy math number theory *1800

Please click on ads to support us..

C++ Code:

#include <iostream>
#include <vector>
#include <unordered_set>
#define sz(x) int(x.size())
using namespace std;


int main() {
    int t;
    cin >> t;

    while (t--) {
        int n, p;
        cin >> n >> p;
        vector<int> digits;
        unordered_set<int> board;
        while (n--) {
            int num;
            cin >> num;
            digits.push_back(num);
            board.insert(num);
        }
        int last_digit = digits[sz(digits) - 1];
        int closest_left = last_digit;
        int operations = 0;
        while(board.find(closest_left) != board.end() && closest_left >= 0)
            closest_left--;
        if(closest_left >= 0){
            operations += p - last_digit;
            for(int i = sz(digits) - 2; i >= 0; i--){
                if(digits[i] != p - 1) {
                    board.insert(digits[i] + 1);
                    break;
                }
                if(i == 0)
                    board.insert(1);
            }
            if(sz(digits) == 1)
                board.insert(1);
            board.insert(0);
            closest_left = last_digit;
            while(board.find(closest_left) != board.end() && closest_left > 0)
                closest_left--;
            operations += closest_left;
        } else {
            int last = p - 1;
            while(board.find(last) != board.end() && last != last_digit)
                last--;
            operations = last - last_digit;
        }

    cout << operations << endl;

    }

    return 0;
}





Comments

Submit
0 Comments
More Questions

977D - Divide by three multiply by two
1654B - Prefix Removals
1654A - Maximum Cake Tastiness
1649A - Game
139A - Petr and Book
1612A - Distance
520A - Pangram
124A - The number of positions
1041A - Heist
901A - Hashing Trees
1283A - Minutes Before the New Year
1654D - Potion Brewing Class
1107B - Digital root
25A - IQ test
785A - Anton and Polyhedrons
1542B - Plus and Multiply
306A - Candies
1651C - Fault-tolerant Network
870A - Search for Pretty Integers
1174A - Ehab Fails to Be Thanos
1169A - Circle Metro
780C - Andryusha and Colored Balloons
1153A - Serval and Bus
1487C - Minimum Ties
1136A - Nastya Is Reading a Book
1353B - Two Arrays And Swaps
1490E - Accidental Victory
1335A - Candies and Two Sisters
96B - Lucky Numbers (easy)
1151B - Dima and a Bad XOR